package model

import (
	"fmt"
	orm "website/dao"
)

type Contact struct {
	Model
	FirstName    string `json:"first_name" gorm:"not null" form:"first_name" binding:"required"`
	LastName     string `json:"last_name" gorm:"not null" form:"last_name" binding:"required"`
	PhoneNumber  string `json:"phone_number" form:"phone_number"`
	Email        string `json:"email" gorm:"not null" form:"email" binding:"required"`
	Organization string `json:"organization" gorm:"not null" form:"organization" binding:"required"`
	Desc         string `json:"desc" form:"desc"`
}

func (c *Contact) CreateContactInfo() (err error) {
	if rows := orm.Easy.Where("email = ? AND phone_number = ? AND organization = ?", c.Email, c.PhoneNumber, c.Organization).Find(&c).RowsAffected; rows != 0 {
		err = fmt.Errorf("记录已存在，不允许重复提交！")
		return err
	}
	if err = orm.Easy.Create(&c).Error; err != nil {
		return err
	}
	return
}

func (c *Contact) FetchAllContactInfo() (cts []Contact, err error) {
	if err = orm.Easy.Find(&cts).Error; err != nil {
		return nil, err
	}
	return
}

func (c *Contact) FetchSingleContactInfo(id int64) (cts []Contact, err error) {
	if err = orm.Easy.Where("id = ?", id).Error; err != nil {
		return nil, err
	}
	return
}
